package com.begye.smartloan.apptest.detailadsource

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtDetailAdSourceBinding
import com.begye.smartloan.apptest.ext.toJSONObjectList
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.huankuan.HuanKuanActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.RenZhengActivity
import com.begye.smartloan.apptest.renzheng.bangka.RenZhengBangKaActivity
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentActivity
import com.begye.smartloan.apptest.renzheng.lianxiren.RenZhengLianXiRenActivity
import com.begye.smartloan.apptest.renzheng.selfie.RenZhengSelfieActivity
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.addTouch
import com.google.android.material.slider.Slider
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.dpToPx
import com.util.utillib.extend.toNextActivity
import org.json.JSONArray


@SuppressLint("CustomWelcomeScreen")
class DetailAdSourceActivity : AppCompatActivity() {

    private lateinit var _binding: AtDetailAdSourceBinding
    private lateinit var _detailAfterItemAdapter1: DetailAfterItemAdapter
    private lateinit var _detailAfterItemAdapter2: DetailAfterItemAdapter
    private lateinit var _detailAfterDayAdapter: DetailAfterDayAdapter

    private val _detailAdSourceViewModel by lazy {
        ViewModelProvider(this)[DetailAdSourceViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtDetailAdSourceBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configUIData()
    }

    private fun configYongHuLiuChengState() {

        _detailAdSourceViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onDoingRenZhengPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengLianXiRenActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingDocumentPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengDocumentActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingSelfiePageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengSelfieActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
//                toNextActivity(
//                    activity = DetailAdSourceActivity::class.java,
//                    mode = IntentFlagMode.SINGLE_TOP
//                )
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIState() {

        _detailAdSourceViewModel.onSliderChangedLiveData.observe(this) {
            it?.let { result ->
                _binding.atDetailAdSourceMaxValue.text = result
            }
        }

        _detailAdSourceViewModel.onCalChangedLiveData.observe(this) {
            it?.let { result ->
                _detailAdSourceViewModel.requestPreviewDetail()

                //
                addTouch(type = "detail_ad_source_slider_changed", remark = result)
            }
        }

        _detailAdSourceViewModel.onShengQingSuccessfulLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = DetailAdSourceProcessingActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _detailAdSourceViewModel.onPreviewDetailLiveData.observe(this) {
            it?.let { result ->
                try {
                    _binding.atDetailAdSourceMaxValue.text = result.optString("amountFormat")

                    val layoutParams = _binding.atDetailAdSourceTop.layoutParams
                    val showFanWei = result.optBoolean("chooseAmountFlag", false)
                    if (showFanWei) {
                        _binding.atDetailAdSourceMaxTitle.text =
                            getText(R.string.detail_before_text_1)

                        _binding.atDetailAdSourceSliderContent.visibility = View.VISIBLE

                        _binding.atDetailAdSourceSliderMin.text =
                            result.optString("minAmountFormat")
                        _binding.atDetailAdSourceSliderMax.text =
                            result.optString("maxAmountFormat")

                        layoutParams.height = dpToPx(290F).toInt()
                        _binding.atDetailAdSourceTop.layoutParams = layoutParams

                        val processFormat = result.optString("processFormat", "0")
                        _binding.atDetailAdSourceSlider.value = processFormat.toFloat()

                    } else {
                        _binding.atDetailAdSourceMaxTitle.text =
                            getText(R.string.detail_before_text_5)

                        _binding.atDetailAdSourceSliderContent.visibility = View.GONE

                        layoutParams.height = dpToPx(220F).toInt()
                        _binding.atDetailAdSourceTop.layoutParams = layoutParams
                    }

                    // days
                    val daysArrayFormat = result.optJSONArray("dasArrayFormat") ?: JSONArray()
                    val daysList = daysArrayFormat.toJSONObjectList()
                    _detailAfterDayAdapter.dataList = daysList
                    _detailAfterDayAdapter.notifyDataSetChanged()

                    // items 1
                    val itemArray1 = result.optJSONArray("itemArray1") ?: JSONArray()
                    val itemList1 = itemArray1.toJSONObjectList()
                    _detailAfterItemAdapter1.dataList = itemList1
                    _detailAfterItemAdapter1.notifyDataSetChanged()

                    // items 2
                    val itemArray2 = result.optJSONArray("itemArray2") ?: JSONArray()
                    val itemList2 = itemArray2.toJSONObjectList()
                    _detailAfterItemAdapter2.dataList = itemList2
                    _detailAfterItemAdapter2.notifyDataSetChanged()

                } catch (e: Exception) {
                    //
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIEvent() {

        _binding.atDetailAdSourceNav.initConfig(
            text = getString(R.string.detail_before_text_6),
            leftResId = R.drawable.dres_5,
            rightResId = R.drawable.dres_4
        ) {
            if (0 == it) {
                val isFinish = intent.getStringExtra("isFinish") ?: ""
                if (isFinish == "YES") {
                    finish()
                } else {
                    toNextActivity(
                        activity = HomeAdSourceActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                }
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _detailAfterItemAdapter1 = DetailAfterItemAdapter(emptyList())
        _detailAfterItemAdapter2 = DetailAfterItemAdapter(emptyList())

        _detailAfterDayAdapter = DetailAfterDayAdapter(emptyList()) {
            _detailAdSourceViewModel.updateDayFromPosition(it)
            _detailAfterDayAdapter.notifyDataSetChanged()
        }

        _binding.atDetailAdSourceItemList1.layoutManager = LinearLayoutManager(this)
        _binding.atDetailAdSourceItemList1.adapter = _detailAfterItemAdapter1

        _binding.atDetailAdSourceItemList2.layoutManager = LinearLayoutManager(this)
        _binding.atDetailAdSourceItemList2.adapter = _detailAfterItemAdapter2

        _binding.atDetailAdSourceDayList.layoutManager = GridLayoutManager(this, 3)
        _binding.atDetailAdSourceDayList.adapter = _detailAfterDayAdapter

        _binding.atDetailAdSourceSlider.addOnChangeListener { _, process, _ ->
            _detailAdSourceViewModel.calSliderChanged(process, true)
        }

        _binding.atDetailAdSourceSlider.addOnSliderTouchListener(object :
            Slider.OnSliderTouchListener {
            override fun onStartTrackingTouch(slider: Slider) {
                // 滑块开始被触摸时的逻辑
            }

            override fun onStopTrackingTouch(slider: Slider) {
                // 滑块停止滑动（放开）时触发的逻辑
                val process = slider.value
                _detailAdSourceViewModel.calSliderChanged(process, false)
            }
        })

        _binding.atDetailAdSourceCommit.setOnClickListener {
            _detailAdSourceViewModel.requestConfirmShenQing()

            //
            addTouch(type = "detail_ad_source_commit_click")
        }

        try {
            val thumbDrawable = ContextCompat.getDrawable(this, R.drawable.dres_31)
            thumbDrawable?.let {
                _binding.atDetailAdSourceSlider.setCustomThumbDrawable(it)
                _binding.atDetailAdSourceSlider.setCustomThumbDrawable(it)
            }
        } catch (e: Exception) {
            //
        }
    }

    private fun configUIData() {
        _detailAdSourceViewModel.requestPreviewDetail()
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

